package sy.controller.base;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.nutz.lang.Mirror;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import sy.pageModel.base.JsonResult;
import sy.pageModel.base.PageResult;
import sy.service.base.BaseService;
import sy.util.base.BeanUtil;
import sy.util.base.DateEditor;
import sy.util.base.QueryFilter;
import sy.util.base.StringEscapeEditor;

/**
 * 基础控制器
 * 
 * 其他控制器继承此控制器获得日期字段类型转换和防止XSS攻击的功能
 * 
 * @author 孙宇
 *
 */
public abstract class BaseController<T extends Serializable, PK extends Serializable> {

	private final Class<T> entityClass;

	protected BaseService<T, PK> service;

	public abstract void setService(BaseService<T, PK> service);

	public BaseController() {
		this.entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}

	@InitBinder
	public void initBinder(ServletRequestDataBinder binder) {
		/**
		 * 自动转换日期类型的字段格式
		 */
		binder.registerCustomEditor(Date.class, new DateEditor());

		/**
		 * 防止XSS攻击，并且带去左右空格功能
		 */
		binder.registerCustomEditor(String.class, new StringEscapeEditor(true, false));
	}

	public JsonResult save(T t) {
		JsonResult j = new JsonResult();
		service.save(t);
		j.setMsg("保存成功");
		j.setSuccess(true);
		j.setObj(t);
		return j;
	}

	public JsonResult delete(PK id) {
		JsonResult j = new JsonResult();
		try {
			service.delete(service.get(id));
			j.setMsg("删除成功");
			j.setSuccess(true);
		} catch (Exception e) {
			j.setMsg("删除失败");
		}
		return j;
	}

	public JsonResult update(T t) {
		JsonResult j = new JsonResult();
		Mirror<?> mirror = Mirror.me(this.entityClass);
		PK id = (PK) mirror.getValue(t, "id");
		T ot = service.get(id);
		if (ot != null) {
			BeanUtil.copyProperties(t, ot);// 一句话将新对象信息覆盖到原数据中
			service.update(ot);
			j.setMsg("更新成功");
			j.setSuccess(true);
			j.setObj(t);
		} else {
			j.setMsg("更新失败，找不到对象");
		}
		return j;
	}

	public JsonResult get(PK id) {
		JsonResult j = new JsonResult();
		j.setSuccess(true);
		j.setObj(service.get(id));
		return j;
	}

	public PageResult find(HttpServletRequest request) {
		QueryFilter filter = new QueryFilter(request);
		PageResult p = new PageResult();

		p.setRows(service.find(filter));
		p.setTotalRows(service.count(filter));
		p.setPage(filter.getPage());
		p.setPageSize(filter.getPageSize());

		return p;
	}

}
